package cn.gs.serializable.serialize;

// @author gs
import cn.gs.serializable.entity.ArrayEntity;
import cn.gs.serializable.entity.IEntity;
import cn.gs.serializable.serialize.ISerialize;
import cn.gs.serializable.serialize.SerializeController;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;

public class CollectionSerialize extends AGenericSerialize {

    public CollectionSerialize() {
    }

    public CollectionSerialize(ISerialize ss) {
        super(ss);
    }

    public CollectionSerialize(Class<?> cc) {
        super(cc);
    }

    @Override
    public <T> T toObj(cn.gs.serializable.serialize.ISerialize ctrl, IEntity from, Class<T> clazz) {
        if (!(from instanceof ArrayEntity) || (clazz != null && !Collection.class.isAssignableFrom(clazz))) {
            return null;
        }
        T coll = create(clazz, new LinkedList());
        List<IEntity> entities = ((ArrayEntity) from).getEntities();
        if (entities.isEmpty()) {
            //no item should be convert.
            return coll;
        }
        if (coll == null || !(coll instanceof Collection)) {
            return null;
        }
        Collection c = (Collection) coll;
        //convert and add items
        for (int i = 0; i < entities.size(); ++i) {
            Object o = serialize(ctrl).toObj(ctrl, entities.get(i), cc);
            c.add(o);
        }
        return coll;
    }

    @Override
    public IEntity fromObj(ISerialize ctrl, Object o) {
        if (o != null && o instanceof Collection) {
            Collection c = (Collection) o;
            List<IEntity> entities = new ArrayList<IEntity>(c.size());
            for (Object f : c) {
                IEntity e = serialize(ctrl).fromObj(ctrl, f);
                entities.add(e);
            }
            return new ArrayEntity(entities);
        }
        return null;
    }
}
